#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include "socklib.h"

void process_request(int *fd);

int main()
{
    int err;
    int sock_id = make_server_socket(1496);
    if (sock_id == -1){
        return -1;
    }
    while(1){
        int fd;
        fd = accept(sock_id,NULL,NULL);
        if (fd == -1){
            break;
        }
        pthread_t tRequest;
        err = pthread_create(&tRequest, NULL, process_request, &fd);
        if (err != 0) {
            perror("pthread_create error");
        }
        err = pthread_join(tRequest, NULL);
        if (err != 0) {
            perror("pthread_join tRequest");
        }
        close(fd);
    }

    return 0;
}

void process_request(int *fd)
{
    int n;
    char buf[128];
    time_t now;
    char *cp;
    time(&now);
    cp = ctime(&now);
	//printf("%s\nlen: %d\n",cp,strlen(cp));
    //write(*fd,cp,strlen(cp));
    printf("Send:%s\n",cp);
    n = sendMsg(*fd, cp, 100);
    if (n < 0) {
        return;
    }
    n = recvMsg(*fd, buf, 128, 100);
    if (n < 0) {
        return;
    }
    printf("Recv:%s\n", buf);
    printf("Send:Sure\n");
    sleep(1);
    n = sendMsg(*fd, "Sure", 100);
    if (n < 0) {
        return;
    }
}

